package controllers

import play.api.mvc._
import play.api.data.Form
import play.api.data.Forms._
import play.api.i18n.Messages
object Users extends Controller {

  val loginForm = Form(tuple(
    "name" -> nonEmptyText,
    "password" -> nonEmptyText).
    verifying(Messages("user.login.error"),u=>models.User.verify(u._1, u._2)))

  def login = Action {
    implicit request =>
      import util._
      if (!request.session.get(Constants.User).isDefined) {
        val form = loginForm
        Ok(views.html.user.login(form))
      } else {
        Redirect(routes.Application.index)
      }
  }

  def doLogin = Action {
    implicit request =>
      val form=loginForm
      form.bindFromRequest().fold(
        errorsForm => Ok(views.html.user.login(errorsForm)),
        user => Redirect(routes.Application.index).withSession(
          session + (util.Constants.User,user._1) 
          + (util.Constants.UserId,models.User.findUser(user._1).id+"")
        )
      )
  }
  
  def logout = Action {
    implicit request =>
      Redirect(routes.Application.index).withNewSession
  }
  
}